package com.djzz.app.common_util.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.djzz.app.common_util.BaseApplication;

/**
 * SharedPreference 管理类
 * Created by d on 2017/8/31.
 */

public class SharedPreference {

    private static String SP_NAME = "djzz_wdy_sp";

    private static void apply(SharedPreferences.Editor editor){

        try {
            editor.apply();
        }catch (Exception e){
            editor.commit();
        }

    }

    private static SharedPreferences getSharedPreference(){
        return BaseApplication.context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
    }

    private static void set(String key, Object value){

        if(value != null){

            SharedPreferences.Editor editor = getSharedPreference().edit();
            String valueType = value.getClass().getSimpleName();
            switch (valueType){
                case "String":
                    editor.putString(key, (String) value);
                    break;
                case "Integer":
                    editor.putInt(key, (Integer)value);
                    break;
                case "Float":
                    editor.putFloat(key, (Float) value);
                    break;
                case "Boolean":
                    editor.putBoolean(key, (Boolean) value);
                    break;
                case "Long":
                    editor.putLong(key, (Long) value);
                    break;
                default:
                    break;
            }

            apply(editor);

        }else{

        }
    }

    private static Object get(String key, Object defValue){
        if(defValue != null){

            SharedPreferences sp = getSharedPreference();
            String valueType = defValue.getClass().getSimpleName();
            switch (valueType){
                case "String":
                    return sp.getString(key, (String)defValue);
                case "Integer":
                    return sp.getInt(key, (Integer)defValue);
                case "Float":
                    return sp.getFloat(key, (Float)defValue);
                case "Boolean":
                    return sp.getBoolean(key, (Boolean)defValue);
                case "Long":
                    return sp.getLong(key, (Long)defValue);
                default:
                    return null;
            }
        }else{
            return null;
        }
    }

    private static void clear(String keys[]){
        SharedPreferences.Editor editor = getSharedPreference().edit();

        if(keys != null && keys.length>0){
            for( int i = 0; i<keys.length; i++){
                editor.remove(keys[i]);
            }
            apply(editor);
        }
    }

    /**
     * 清空所有内容
     */
    private static void clear(){

        SharedPreferences.Editor editor = getSharedPreference().edit();
        editor.clear();
        apply(editor);
    }
}
